package com.gps.skyrc.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleReadCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.gps.skyrc.R;
import com.gps.skyrc.activity.base.BaseActivity;
import com.gps.skyrc.api.Config;
import com.gps.skyrc.api.EventBusCode;
import com.gps.skyrc.bean.DeviceInfo;
import com.gps.skyrc.bean.EventBusMessage;
import com.gps.skyrc.data.ParseData;
import com.gps.skyrc.tool.EventBusUtils;
import com.gps.skyrc.tool.MyTitleBar;
import com.gps.skyrc.tool.RenameDialog;
import com.gps.skyrc.tool.SharedPreferencesUtils;
import com.gps.skyrc.tool.Tip;
import com.gps.skyrc.tool.TwoChooseDialog;
import com.gps.skyrc.tool.logger.ILogger;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.LitePal;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;

public class AppSettingActivity extends BaseActivity implements View.OnClickListener, RenameDialog.onRenameOnclickListener {
    @BindView(R.id.setting_title)
    MyTitleBar mTitleBar;
    @BindView(R.id.history_rl)
    RelativeLayout mHitoryRl;
    @BindView(R.id.unit_rl)
    RelativeLayout mUnitRl;
    @BindView(R.id.cleanCache_rl)
    RelativeLayout mCleanCacheRl;
    @BindView(R.id.version_tv)
    TextView mVersionTv;
    @BindView(R.id.name_rl)
    RelativeLayout mNameRl;
    @BindView(R.id.name_tv)
    TextView mName;
    private BleDevice mBleDevice;
    private String mLastMac;
    private int mOffLine;
    private TwoChooseDialog mDialog;
    private DeviceInfo mDevice;
    private RenameDialog mRenameDialog;
    private String mNewName;

    @Override
    protected void getLayout() {
        setContentView(R.layout.activity_setting);
    }

    @Override
    protected void setTitleBar() {
        mTitleBar.initViewsVisible(true, false, false, true, false, true);
        mTitleBar.setOnLeftButtonClickListener(v -> onBackPressed());
    }

    @Override
    protected void init() {
        mOffLine = getIntent().getIntExtra("offLine", 0);
        if (mOffLine == 1) {//在线
            mBleDevice = getIntent().getParcelableExtra(Config.BLE_SEND_BLEDEVICE);
            mDevice = getIntent().getParcelableExtra("deviceInfo");
            getVersion();
        } else {//离线
            List<DeviceInfo> mDeviceInfos = LitePal.findAll(DeviceInfo.class);
            mLastMac = (String) SharedPreferencesUtils.getParam(mContext, SharedPreferencesUtils.PreKey.LAST_DEVICE_MAC, "");
            for (int i = 0; i < mDeviceInfos.size(); i++) {
                if (mDeviceInfos.get(i).getMac().equals(mLastMac)) {
                    mDevice = mDeviceInfos.get(i);
                    mVersionTv.setText("V" + mDeviceInfos.get(i).getVersion());
                }
            }
            mName.setText(Config.BLE_FIRST_CONNECT + mLastMac.substring(12).replace(":", ""));
        }

        if (!mDevice.getName().equals(""))
            mName.setText(mDevice.getName());

        mHitoryRl.setOnClickListener(this);
        mUnitRl.setOnClickListener(this);
        mCleanCacheRl.setOnClickListener(this);
        mNameRl.setOnClickListener(this);
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    //查看设备版本
    private void getVersion() {
        BleManager.getInstance().read(mBleDevice, Config.UUID_SERVICE, Config.UUID_VERSION_UPGRADE, new BleReadCallback() {
            @Override
            public void onReadSuccess(byte[] data) {//已经转成10进制
                Float version = ParseData.parseVersion(data);
                mVersionTv.setText("V" + version);
                checkHaveName();
            }

            @Override
            public void onReadFailure(BleException exception) {
                Tip.showToast(mContext, R.string.get_version_error);
            }
        });
    }

    //检查是否有名字
    private void checkHaveName() {
        if (mName.getText().toString().trim().length() <= 0)
            getDeviceName();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.history_rl:
                Bundle bundle = new Bundle();
                bundle.putInt("offLine", mOffLine);
                if (mOffLine == 1)
                    bundle.putParcelable(Config.BLE_SEND_BLEDEVICE, mBleDevice);
                startActivity(HistoryDataTotalActivity.class, bundle);
                break;
            case R.id.unit_rl:
                startActivity(UnitActivity.class);
                break;
            case R.id.cleanCache_rl:
                if (mOffLine == 1) {//在线才能清除
                    mDialog = new TwoChooseDialog(mContext, getString(R.string.clean_cache_prompt), getString(R.string.confirm));
                    mDialog.show();
                    CleanCacheListener();
                }
                break;
            case R.id.name_rl:
                if (mOffLine != 1) {//在线才能修改名字
                    Tip.showToast(mContext, R.string.device_offline);
                } else {
                    mRenameDialog = new RenameDialog(mContext, mDevice.getName(), getString(R.string.app_name));
                    mRenameDialog.setRenameOnclickListener(this);
                    mRenameDialog.show();
                }
                break;
        }
    }

    private void CleanCacheListener() {
        mDialog.setClickListener(new TwoChooseDialog.TwoClickListener() {
            @Override
            public void confirm() {
                mDialog.dismiss();
                Tip.showLoadDialog(mContext);
                cleanCache();
            }

            @Override
            public void cancel() {
                mDialog.dismiss();
            }
        });
    }

    private void cleanCache() {
        byte[] cmd = {0x0f, 0x05, 0x08, 0, 0, 0, 0, (byte) 0xff, (byte) 0xff};
        int checksum = 1;
        for (int i = 2; i < 6; i++)
            checksum += cmd[i];
        cmd[6] = (byte) (checksum & 0xFF);
        ILogger.d("test:" + Arrays.toString(cmd));
        BleManager.getInstance().write(mBleDevice, Config.UUID_SERVICE, Config.UUID_WRITE, cmd, new BleWriteCallback() {
            @Override
            public void onWriteSuccess(int current, int total, byte[] justWrite) {
                Tip.closeLoadDialog();
                ILogger.d("发送成功");
            }

            @Override
            public void onWriteFailure(BleException exception) {
                Tip.closeLoadDialog();
                Tip.showToast(mContext, R.string.send_error);
            }
        });
    }

    private void getDeviceName() {
        BleManager.getInstance().read(mBleDevice, Config.UUID_SERVICE, Config.UUID_READ_NAME, new BleReadCallback() {
            @Override
            public void onReadSuccess(byte[] data) {
                try {
                    String name = new String(data, "UTF-8");
                    mName.setText(name);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onReadFailure(BleException exception) {

            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSubEventBus(EventBusMessage message) {
        int code = message.getCode();
        if (code == EventBusCode.EVENT_BUS_CLEAN_CACHE_RESPONE) {
            byte[] data = (byte[]) message.getData();
            ILogger.d(Arrays.toString(data));
            int respone = ParseData.parseCleanCache(data);
            if (respone == 0) {
                Tip.showToast(mContext, R.string.clean_cache_success);
            } else if (respone == 1) {
                Tip.showToast(mContext, R.string.clean_cache_error);
            }
        } else if (code == EventBusCode.EVENT_BUS_NAME_MODIFY) {
            byte[] data = (byte[]) message.getData();
            //有应答就代表成功
            mDevice.setName(mNewName);
            mName.setText(mNewName);
        }

    }

    @Override
    public void onRenamecancelClick(View view) {
        mRenameDialog.dismiss();
    }

    @Override
    public void onRenameconfirmClick(String name) {
        rename(name);
    }


    private void rename(String name) {
        byte[] cmd = {0x0f, 0x17, 0x05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (byte) 0xff, (byte) 0xff};
        byte[] nameBytes = name.getBytes();
        for (int i = 0; i < nameBytes.length; i++) {
            cmd[4 + i] = nameBytes[i];
        }
        int checksum = 1;
        for (int k = 2; k < 24; k++)
            checksum += cmd[k];
        cmd[24] = (byte) (checksum & 0xFF);
        BleManager.getInstance().write(mBleDevice, Config.UUID_SERVICE, Config.UUID_WRITE, cmd, new BleWriteCallback() {
            @Override
            public void onWriteSuccess(int current, int total, byte[] justWrite) {
                mNewName = name;
                mRenameDialog.dismiss();
            }

            @Override
            public void onWriteFailure(BleException exception) {
                Tip.showToast(mContext, getString(R.string.send_error));
                mRenameDialog.dismiss();
            }
        });
    }
}
